#include <omp.h>
#include <stdio.h>

void flush_incorrect() {
    int a, b;
    a = b = 0;
    #pragma omp parallel num_threads(2)
    {
        int thread_num = omp_get_thread_num();
        int tmp;

        if (thread_num == 0) {
            // 线程 0 写入 b 并刷新
            printf("Thread %d: Initial a is %d, b is %d\n", thread_num, a, b);
            #pragma omp atomic write
            b = 1;
            printf("Thread %d: Setting b to 1\n", thread_num);
            #pragma omp flush(b)
            printf("Thread %d: Flushed b\n", thread_num);
            #pragma omp flush(a)
            printf("Thread %d: Flushed a\n", thread_num);
            #pragma omp atomic read
            tmp = a;
            printf("Thread %d: Read a as %d\n", thread_num, tmp);
        } else {
            // 线程 1 写入 a 并刷新
            printf("Thread %d: Initial a is %d, b is %d\n", thread_num, a, b);
            #pragma omp atomic write
            a = 1;
            printf("Thread %d: Setting a to 1\n", thread_num);
            #pragma omp flush(a)
            printf("Thread %d: Flushed a\n", thread_num);
            #pragma omp flush(b)
            printf("Thread %d: Flushed b\n", thread_num);
            #pragma omp atomic read
            tmp = b;
            printf("Thread %d: Read b as %d\n", thread_num, tmp);
        }
        if (tmp == 0) {
            printf("Thread %d: Entered protected section (tmp is %d)\n", thread_num, tmp);
            // protected section
        } else {
            printf("Thread %d: Did not enter protected section (tmp is %d)\n", thread_num, tmp);
        }
    }
}

int main() {
    flush_incorrect();
    return 0;
}
